package main.java.org.service.serviceImpl;


import lombok.extern.slf4j.Slf4j;
import main.java.Exam.pojo.Entity.*;
import main.java.Exam.pojo.tableDTO.ClassTeacherDTO;
import main.java.Exam.pojo.tableDTO.ExamDTO;
import main.java.Exam.pojo.tableDTO.ExamPageDTO;
import main.java.org.mapper.ExamMapper;
import main.java.org.mapper.LogMapper;
import main.java.org.mapper.QuestionMapper;
import main.java.org.mapper.UserMapper;
import main.java.org.result.Result;
import main.java.org.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.LocalDateTime;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class ExamServiceImpl implements ExamService {
    @Autowired ExamMapper examMapper;
             //添加考试
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    LogMapper logMapper;


    @Override
    public void createxam(ExamDTO examDTO) {
        //校验开始时间和结束时间非空
        LocalDateTime startTime = examDTO.getStartTime();
        LocalDateTime endTime = examDTO.getEndTime();
        if (startTime == null || endTime == null) {
            throw new IllegalArgumentException("考试开始时间和结束时间不能为空");
        }
        //校验结束时间必须晚于开始时间
        if (endTime.isBefore(startTime)) {
            throw new IllegalArgumentException("考试结束时间不能早于开始时间");
        }
        //计算时间差（转换为分钟）
        Duration duration = Duration.between(startTime, endTime); // 计算两个时间的间隔
        long minutes = duration.toMinutes(); // 转换为分钟
        //设置考试时长（testTime）
        examDTO.setTestTime((int) minutes);
       //根据时间计算状态
        String testStatus="未开始";
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(startTime)) {
            testStatus = "未开始";     //未开始
        } else if (now.isAfter(endTime)) {
            testStatus = "已结束";     //已完成
        } else {
            testStatus = "进行中";     //进行中
        }

      //  logexam(examDTO.getUserAccount(),userMapper.getuserName(examDTO.getUserAccount()),"创建考试","考试模块");
        //添加到数据库
        examDTO.setTestStatus(testStatus);
        examMapper.add(examDTO);

    }
       //编辑考试
    @Override
    public void bianjiexam(ExamDTO examDTO) {
        LocalDateTime startTime = examDTO.getStartTime();
        LocalDateTime endTime = examDTO.getEndTime();
        //计算时间差（转换为分钟）
        Duration duration = Duration.between(startTime, endTime); // 计算两个时间的间隔
        long minutes = duration.toMinutes(); // 转换为分钟
        //设置考试时长
        examDTO.setTestTime((int) minutes);
        //根据时间计算状态
        String testStatus="未开始";
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(startTime)) {
            testStatus = "未开始";     //未开始
        } else if (now.isAfter(endTime)) {
            testStatus = "已结束";     //已完成
        } else {
            testStatus = "进行中";     //进行中
        }
        //设置考试状态
        examDTO.setTestStatus(testStatus);
       // logexam(examDTO.getUserAccount(),userMapper.getuserName(examDTO.getUserAccount()),"编辑考试","考试模块");

        examMapper.update(examDTO);
    }

        //获取考试
    @Override
    public Result<ExamPageDTO> getexam(String userAccount) {
        if (userAccount == null || userAccount.trim().isEmpty()) {
            log.error("获取老师试卷失败：账号为空");
           throw  new RuntimeException("账号不能为空");
        }
        //查询该老师的所有考试
        List<ExamDTO> examList = examMapper.getexam(userAccount);
        int total = examList.size(); // 总条数

        //组装返回数据（total和paperCount可根据业务调整，这里默认相同）
        ExamPageDTO pageDTO = new ExamPageDTO();
        pageDTO.setTotal(total);
        pageDTO.setPaperCount(total); // 试卷数量=总条数
        pageDTO.setRecords(examList);

     //   logexam(userAccount,userMapper.getuserName(userAccount),"获取考试","考试模块");
        return Result.success( pageDTO);
    }



    //删除考试  @Override
    public void delete(ExamDTO examDTO) {
                  if(examDTO.getUserAccount()==null || examDTO.getTestId()==null){
                      throw new RuntimeException("需要试卷的id和创建者");
                  }
      //  logexam(examDTO.getUserAccount(),userMapper.getuserName(examDTO.getUserAccount()),"删除考试","考试模块");
                examMapper.delete(examDTO.getTestId(),examDTO.getUserAccount());

    }
//显示题目
@Override
public List<Questtion> getQuestionsByExam(List<TestQuestion> questions) {
    return questionMapper.selectByTypeAndIds(questions);
}



    //给老师看所有学生考试信息
    @Override
    public List<ClassTeacherDTO> getStudentExam(Integer testId) {
        //判断考试是否存在
        if(examMapper.getIdTest(testId)==null){
            throw new RuntimeException("没有这个考试");
        }
        // 1. 获取当前考试的所有学生信息
        List<ClassTeacher> classTeacherList = examMapper.getstudentexam(testId);
        if (classTeacherList == null || classTeacherList.isEmpty()) {
            return new ArrayList<>();     // 无数据时返回空列表
        }

        //创建一个 DTO 对象（存储所有学生列表 + 统计信息）
        ClassTeacherDTO dto = new ClassTeacherDTO();

        //给 DTO 的 classTeacher 字段赋值（存入所有学生信息）
        dto.setClassTeacher(classTeacherList);

        //参加考试的人数
        int participantNumber = classTeacherList.size();
        dto.setParticipantNumber(participantNumber);

         log.info("统计信息");
        //最高分
        int highestScore = examMapper.geimax(testId);
        //最低分
        int lowestScore = examMapper.getmin(testId);
         // 及格人数
        int passCount = examMapper.pass(testId);
        //最高分和最低分
        dto.setHighestScore(highestScore);
        dto.setLowestScore(lowestScore);
        //平均分（取整）
        int averageScore = examMapper.average(testId);
        dto.setAverageScore(averageScore);

        //及格率（百分比格式）
        String passRate = "0.0";
        if (participantNumber > 0) {
            double rate = (double) passCount / participantNumber * 100;
            passRate = String.format("%.1f", rate);
        }
        dto.setPassRate(passRate);

        //将DTO放入列表返回
        List<ClassTeacherDTO> resultList = new ArrayList<>();
        resultList.add(dto);
      //  logexam("123312123","陈平安","查看考试信息","考试模块");
        return resultList;
    }






    //给所有考生考试
    @Override
    public Result<ExamPageDTO> getuserexam() {
        // 查询该老师的所有考试
        List<ExamDTO> examList = examMapper.getuserexam();
        int total = examList.size(); // 总条数

        //组装返回数据（total和paperCount可根据业务调整，这里默认相同）
        ExamPageDTO pageDTO = new ExamPageDTO();
        pageDTO.setTotal(total);
        pageDTO.setPaperCount(total); // 试卷数量=总条数
        pageDTO.setRecords(examList);
        return Result.success(pageDTO);
    }
  //获取单个考试
    @Override
    public exam getSigneleTest(Integer testId) {
        exam idTest = examMapper.getIdTest(testId);
        if(idTest==null){
            throw new IllegalArgumentException("没有这个考试");
        }
        return examMapper.getIdTest(testId);
    }

    // AI自动批改题目实现
    @Override
    public int aiMark(Integer questionId, String answer,Integer testId,String userAccount) {
        // 获取题目信息
        log.info("账号{},testId{}",userAccount,testId);
        Questtion question = questionMapper.getQuestionById(questionId);
        if (question == null) return 0;
        String prompt = "请根据以下题目和标准答案，对学生答案进行评分，只给我分数（0-" + question.getScore() + "），只返回数字分数，不要其他内容。\n"
            + "题目：" + question.getContent() + "\n"
            + "标准答案：" + question.getAnswer() + "\n"
            + "学生答案：" + answer;
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://api.siliconflow.cn/v1/chat/completions";//https://api.siliconflow.cn/v1/chat/completions
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth("sk-xbdjasaicppkwdumcvvdwehjeesknxoxsfzudxszmnyucwnv");
            ObjectMapper mapper = new ObjectMapper();
            String body = mapper.writeValueAsString(Map.of(
                "model", "Qwen/Qwen3-32B",//"model": "siliconflow-chat"
                "messages", List.of(Map.of("role", "user", "content", prompt))
            ));
            HttpEntity<String> entity = new HttpEntity<>(body, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            log.info("AI的对话{}",response.getBody());
            // 解析AI返回的分数
            String aiScoreStr = mapper.readTree(response.getBody())
                .path("choices").get(0).path("message").path("content").asText().replaceAll("[^0-9]", "");
            Integer stuScore=Integer.parseInt(aiScoreStr);
                  log.info("计算得分为：{}",stuScore);
                  if(examMapper.getaaa(stuScore,testId,userAccount)==null){
            examMapper.getscore(stuScore,testId,userAccount);}

            return Integer.parseInt(aiScoreStr);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }





}
